<?php


namespace app\middleware;


use app\model\Log;

class LogRecord
{
    public function handle($request, \Closure $next)
    {
        //前置逻辑
        $path = $request->url();
        $method = $request->method();
        $data = json_encode(input('get.'),JSON_UNESCAPED_UNICODE);
        $ip = $this->getip()=="::1"?"localhost":$this->getip();
        $time = date("Y-m-d h:i:s");
        Log::create(["ip"=>$ip,"method"=>$method,"path"=>$path,"data"=>$data,"create_time"=>$time]);
        $res = $next($request);

        //后置逻辑

        return $res;
    }
    public function end(){

    }
    function getip() {

        static $ip = '';

        $ip = $_SERVER['REMOTE_ADDR'];

        if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {

            $ip = $_SERVER['HTTP_CDN_SRC_IP'];

        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {

            $ip = $_SERVER['HTTP_CLIENT_IP'];

        } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {

            foreach ($matches[0] AS $xip) {

                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {

                    $ip = $xip;

                    break;

                }

            }

        }

        return $ip;

    }
}